/**
 * 
 */
package com.rd.sys.service.sys.user.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import baseproj.common.exception.BaseServiceException;
import baseproj.component.log.LoggerAdapter;
import baseproj.component.log.LoggerService;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.utils.crypto.MD5;
import com.rd.sys.common.web.session.SessionUtil;
import com.rd.sys.dto.sys.user.UserInfoDto;
import com.rd.sys.dto.sys.user.UserLoginDto;
import com.rd.sys.service.sys.user.UserAllInOneService;
import com.rd.sys.service.sys.user.UserLoginService;

/**
 * @author
 * 
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class UserLoginServiceImpl implements UserLoginService {
    private final LoggerService logger = LoggerAdapter.getLoggerService(getClass());

    @Autowired
    private UserAllInOneService userAllInOneService;

    /**
     * 登录用户门户
     * 
     * @param loginInfo
     * @return 若登录成功,返回需要保存到Session中的用户信息
     * @throws Exception
     */
    @Transactional(readOnly = true)
    public UserInfoDto loginPortal(UserLoginDto loginInfo, HttpServletRequest request) throws Exception {
        try {
            checkLoginValidcode(loginInfo, request);

            if (loginInfo.getUserInputName().toLowerCase()
                    .startsWith(CommonConstants.UserConstats.USER_CODE_PRIFIX.toLowerCase())) { // 以用户编码登录
                loginInfo.setUsercode(loginInfo.getUserInputName());
            } else { // 以自定义的用户名登录
                loginInfo.setName(loginInfo.getUserInputName());
            }

            UserInfoDto user = loginPortal(loginInfo, true);
            logger.info("User[" + user.getUsercode() + "] login portal successful!");

            return user;
        } catch (BaseServiceException be) {
            throw be;
        } catch (Exception e) {
            logger.error("", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录用户门户(通过客户端授权方式)
     * 
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Transactional(readOnly = true)
    public UserInfoDto loginPortalByAuth(UserLoginDto loginInfo) throws Exception {
        try {
            return loginPortal(loginInfo, false);

        } catch (BaseServiceException be) {
            throw be;
        } catch (Exception e) {
            logger.error("", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录用户门户,同时支持普通门户登录 or 客户端通过授权登录
     * 
     * @param loginInfo
     * @param isCheckPassword
     *            是否需要校验密码正确
     * @return
     * @throws Exception
     */
    @Transactional(readOnly = true)
    private UserInfoDto loginPortal(UserLoginDto loginInfo, boolean isCheckPassword) throws Exception {
        UserInfoDto userInfo = userAllInOneService.selectUserInfo(loginInfo.getUsercode());

        /* 首先判断用户是否存在 */
        if (userInfo == null) {
            throw new UserLoginServiceException(UserLoginServiceException.ACCOUNT_OR_PASSWORD_ERROR);
        }
        /* 再判断密码是否正确 */
        if (isCheckPassword) {
            String pwd = MD5.encrypt(loginInfo.getPassword());
            if (!pwd.equalsIgnoreCase(userInfo.getPassword())) {
                throw new UserLoginServiceException(UserLoginServiceException.ACCOUNT_OR_PASSWORD_ERROR);
            }
        }

        /* 设置返回的用户信息 */
        UserInfoDto rtnUser = new UserInfoDto();
        rtnUser.setUserno(userInfo.getUserno());
        rtnUser.setUsercode(userInfo.getUsercode());
        rtnUser.setNickname(userInfo.getNickname());
        rtnUser.setName(userInfo.getName());
        rtnUser.setTelephone(userInfo.getTelephone());
        rtnUser.setEmail(userInfo.getEmail());

        return rtnUser;
    }

    /**
     * 检查登录验证码
     * 
     * @param loginInfo
     * @param request
     * @throws Exception
     */
    private void checkLoginValidcode(UserLoginDto loginInfo, HttpServletRequest request) throws Exception {
        HttpSession session = SessionUtil.getSession(request);

        String validcode = loginInfo.getValidcode();
        String sesValidCode = (String) session.getAttribute("validCode");
        if (!sesValidCode.equals(validcode)) {
            throw new UserLoginServiceException(UserLoginServiceException.LOGIN_VALIDCODE_INVALID);// 验证码不正确
        }

    }
}
